package com.gwt.tirso.gymkhana.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.tirso.gymkhana.client.Gymkhana;
import com.gwt.tirso.gymkhana.client.IGymkhanaService;
import com.gwt.tirso.gymkhana.client.Person;
import com.gwt.tirso.gymkhana.client.Question;

@SuppressWarnings("serial")
public class GymkhanaServiceImpl extends RemoteServiceServlet implements
		IGymkhanaService {

	/*
	 * private IGymkhanaDAO gdao = new JDBCGymkhanaDAO(); private IQuestionDAO
	 * qdao = new JDBCQuestionDAO(); private IQuestReferencesDAO qrdao = new
	 * JDBCQuestReferencesDAO();
	 */

	@Override
	public Gymkhana createGymkhana(Gymkhana g) throws IllegalArgumentException {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Gymkhana gaux = null;

		Transaction tx = pm.currentTransaction();

		try {

			tx.begin();

			pm.makePersistent(g);

			tx.commit();
			
			gaux = pm.detachCopy(g);

		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}

			pm.close();
		}
		/*
		 * gdao.insertGymkhana(g); for(int i = 0; i < lq.size(); i++){
		 * qdao.insertQuestion(lq.get(i)); qrdao.insertQuestionReference(g,
		 * lq.get(i)); }
		 */
		return gaux;
	}

	@Override
	public Question insertQuestion(Question q) throws IllegalArgumentException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Question qaux;

		try {

			qaux = pm.makePersistent(q);

		} finally {
			
			pm.close();
		}
		return qaux;
	}
	
	@Override
	public String checkName(String name){
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String s = null;
		List<Gymkhana> lg;
		
		try{
			String query = "select from " + Gymkhana.class.getName() + " where name == '" + name + "'";
			lg = (List<Gymkhana>) pm.newQuery(query).execute();
			if(lg.size() > 0){
				s = lg.get(0).getName();
			}
			
		}finally{
			pm.close();
		}
		return s;
	}

}
